/*!
 * New Resource Strategy.
 * Date: 2015/12/31.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
  'jquery',
	'pageInit',
  'formAjax',
  'notification',
  'dateRange',
  'moment',
  'select2',
  'jsTree'
], function ($, vamakerPage, formAjax, VamOpMsg, DateRange, moment, select2, jsTree) {
  $(function () {
    var $dataFrm = $('#data-frm'),
      $submitBtn = $dataFrm.find('button[type="submit"]'),
      dataFieldRule, options, dataValidator,
      strategyName = $('#strategy_name').val(),
      $operateBtn = $submitBtn.filter('.save-btn'),
      $operateType = $dataFrm.find('.operate-type'),
      // RTB资源 wrapper
      $rtbResourceSetting = $('#rtb_resource_type'),
      // 资源包类型
      $packType = $('.pack-type'),
      // 定向类型
      $adspaceBlack = $('input[name="adspace.black_white_radio"]'),
      // 包含范围类型
      $AdspaceCheck = $dataFrm.find('input[name="adspace_check"]'),
      // APP资源包列表
      $appPackListContainer = $('#app-pack-list-container'),
      // WAP资源包列表
      $wapPackListContainer = $('#wap-pack-list-container'),
      // 资源包选择隐藏域
      $packSelectedList = $('#pack_selected_list'),
      // 错误提示框
      $rtbTargetPackErr = $('#rtb_target_pack_err'),
      // APP缩略图
      $appThumbnailPreview = $('#app-thumbnail-preview'),
      // 资源包 wrapper
      $packForm = $('#target_pack_form');
      // console.log($dataFrm);

    $appPackListContainer
      .jstree({
      core: {
        expand_selected_onload: false
      },
      plugins: ["checkbox"],
    }).on("changed.jstree", function (e, data) {
      // console.log(data.selected);
      var
        actionType = data.action,
        selectedNode = data.selected;
      // console.log($packNode.children('.jstree-anchor'));
      // console.log($packNode.children('.jstree-anchor').find('.jstree-undetermined'));
      if ($packType.filter(':checked').val() === '1') {
        $packSelectedList.val(selectedNode.join(','));
      }
      if (actionType !== 'ready') {
        setTimeout(function() {
          var
            $packNode = $appPackListContainer.find('.jstree-undetermined');
          // console.log($packNode);
          $packNode.each(function (index, ele) {
            var
              $meAnchor = $(ele).parent(),
              // $currentPack = $meNode.children('.jstree-anchor'),
              $currentApp = $meAnchor.siblings('.jstree-children').find('.jstree-anchor'),
              $currentSelectApp = $currentApp.filter('.jstree-clicked');
            // console.log($meNode);
            // console.log($currentApp);
            // console.log($currentSelectApp);
            // Half checked && current pack is not empty.
            if (($currentApp.length >= 3 && $currentSelectApp.length < 3)
                || ($currentApp.length < 3 && $currentApp.length !== $currentSelectApp.length)
            ) {
              $rtbTargetPackErr.html('<em class="checky-default-failure">' + VAM.j('Select at least 3 apps in a single resource pack!') + '</em>');
              return false;
            } else {
              $rtbTargetPackErr.html('');
            }
          });
          if ($packNode.length === 0) {
            $rtbTargetPackErr.html('');
          }
        }, 100);
      }
      if (selectedNode.length === 0) {
        $rtbTargetPackErr.html('<em class="checky-default-failure">' + VAM.j('Please select at least one!') + '</em>');
      }
    }).on("hover_node.jstree", function (e, data) {
      var
        node = data.node
        isLeaf = node.parent !== '#';
      // console.log(data);
      if (isLeaf && node.data.thumbnail !== '') {
        $appThumbnailPreview.removeClass('vam-hidden').prop('src', node.data.thumbnail);
      } else {
        $appThumbnailPreview.addClass('vam-hidden').removeProp('src');
      }
    }).on("dehover_node.jstree", function (e, data) {
      var
        node = data.node
        isLeaf = node.parent !== '#';
      // console.log(data);
      if (isLeaf) {
        $appThumbnailPreview.addClass('vam-hidden').removeProp('src');
      }
    });

    $wapPackListContainer
      .jstree({
      core: {
        expand_selected_onload: false
      },
      plugins: ["checkbox"],
    }).on("changed.jstree", function (e, data) {
      // console.log(data.selected);
      var
        actionType = data.action,
        selectedNode = data.selected,
        $packNode = $wapPackListContainer.find('.jstree-undetermined');
      // console.log($packNode.children('.jstree-anchor'));
      // console.log($packNode.children('.jstree-anchor').find('.jstree-undetermined'));
      if ($packType.filter(':checked').val() === '2') {
        $packSelectedList.val(selectedNode.join(','));
      }
      if (actionType !== 'ready') {
        // console.log($packNode);
        setTimeout(function() {
          var
            $packNode = $appPackListContainer.find('.jstree-undetermined');
          // console.log($packNode);
          $packNode.each(function (index, ele) {
            var
              $meAnchor = $(ele).parent(),
              // $currentPack = $meNode.children('.jstree-anchor'),
              $currentApp = $meAnchor.siblings('.jstree-children').find('.jstree-anchor'),
              $currentSelectApp = $currentApp.filter('.jstree-clicked');
            // console.log($meNode);
            // console.log($currentApp);
            // console.log($currentSelectApp);
            // Half checked && current pack is not empty.
            if (($currentApp.length >= 3 && $currentSelectApp.length < 3)
                || ($currentApp.length < 3 && $currentApp.length !== $currentSelectApp.length)
            ) {
              $rtbTargetPackErr.html('<em class="checky-default-failure">' + VAM.j('Select at least 3 apps in a single resource pack!') + '</em>');
              return false;
            } else {
              $rtbTargetPackErr.html('');
            }
          });
          if ($packNode.length === 0) {
            $rtbTargetPackErr.html('');
          }
        }, 100);
      }
      if (selectedNode.length === 0) {
        $rtbTargetPackErr.html('<em class="checky-default-failure">' + VAM.j('Please select at least one!') + '</em>');
      }
    }).on("hover_node.jstree", function (e, data) {
      var
        node = data.node
        isLeaf = node.parent !== '#';
      // console.log(data);
      if (isLeaf && node.data.thumbnail !== '') {
        $appThumbnailPreview.removeClass('vam-hidden').prop('src', node.data.thumbnail);
      } else {
        $appThumbnailPreview.addClass('vam-hidden').removeProp('src');
      }
    }).on("dehover_node.jstree", function (e, data) {
      var
        node = data.node
        isLeaf = node.parent !== '#';
      // console.log(data);
      if (isLeaf) {
        $appThumbnailPreview.addClass('vam-hidden').removeProp('src');
      }
    });

    $adspaceBlack.on('change', function(){
      var $me = $(this),
          $targetForm = $('.target-form'),
          packCheck = $AdspaceCheck.filter(':checked').val(),
          packTypeChecked = $packType.filter(':checked').val();
      // console.log($me.val());
      // console.log(packTypeChecked);
      if ($me.val() === 'no_limit') {
        $targetForm.addClass('vam-hidden');
        if (packTypeChecked === '1') {
          $appPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.addClass('vam-hidden');
          $appPackListContainer.jstree(true).select_all();
        } else if (packTypeChecked === '2') {
          $appPackListContainer.addClass('vam-hidden');
          $wapPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.jstree(true).select_all();
        }
      } else {
        if (packCheck === 'all') {
          if (packTypeChecked === '1') {
            $appPackListContainer.removeClass('vam-hidden');
            $wapPackListContainer.addClass('vam-hidden');
            $appPackListContainer.jstree(true).select_all();
          } else if (packTypeChecked === '2') {
            $appPackListContainer.addClass('vam-hidden');
            $wapPackListContainer.removeClass('vam-hidden');
            $wapPackListContainer.jstree(true).select_all();
          }
        } else {
          if (packTypeChecked === '1') {
            $appPackListContainer.removeClass('vam-hidden');
            $wapPackListContainer.addClass('vam-hidden');
            $appPackListContainer.jstree(true).deselect_all();
          } else if (packTypeChecked === '2') {
            $appPackListContainer.addClass('vam-hidden');
            $wapPackListContainer.removeClass('vam-hidden');
            $wapPackListContainer.jstree(true).deselect_all();
          }
        }
        $targetForm.removeClass('vam-hidden');
      };
    });

    $packType.on('change', function (evt) {
      var
        $me = $(this),
        meVal = $me.val(),
        adspaceBlack = $adspaceBlack.filter(':checked').val(),
        adspaceCheck = $AdspaceCheck.filter(':checked').val();

      // console.log(adspaceBlack);
      // console.log(adspaceCheck)
      // console.log(meVal);

      if (adspaceBlack !== 'no_limit') {
        $packForm.removeClass('vam-hidden');
        // if (adspaceCheck === 'part') {
        // $packSelectedList.val('');
        $rtbTargetPackErr.html('');
        if (meVal === '1') {
          $appPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.addClass('vam-hidden');
          $appPackListContainer.jstree(true).select_all();
        } else if (meVal === '2') {
          $appPackListContainer.addClass('vam-hidden');
          $wapPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.jstree(true).deselect_all();
        }
        // }
      } else {
        $packForm.addClass('vam-hidden');
        $rtbTargetPackErr.html('');
        if (meVal === '1') {
          $appPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.addClass('vam-hidden');
          $appPackListContainer.jstree(true).select_all();
        } else if (meVal === '2') {
          $appPackListContainer.addClass('vam-hidden');
          $wapPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.jstree(true).deselect_all();
        }
      }
    })

    $AdspaceCheck.on('change', function (evt) {
      var $me = $(this),
          meVal = $me.val(),
          packTypeChecked = $packType.filter(':checked').val();
      // console.log(packTypeChecked);
      // console.log(meVal);
      if (meVal === 'all') {
        $packForm.removeClass('vam-hidden');
        // $packType.trigger('change');
        if (packTypeChecked === '1') {
          $appPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.addClass('vam-hidden');
          $appPackListContainer.jstree(true).select_all();
        } else if (packTypeChecked === '2') {
          $appPackListContainer.addClass('vam-hidden');
          $wapPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.jstree(true).select_all();
        }
      } else {
        $packForm.removeClass('vam-hidden');
        if (packTypeChecked === '1') {
          $appPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.addClass('vam-hidden');
          $appPackListContainer.jstree(true).deselect_all();
        } else if (packTypeChecked === '2') {
          $appPackListContainer.addClass('vam-hidden');
          $wapPackListContainer.removeClass('vam-hidden');
          $wapPackListContainer.jstree(true).deselect_all();
        }
      };
      $('#rtb_target_pack_err').html('');
    });

    $submitBtn.on('click', function (evt) {
      var $me = $(this),
        operate = $me.data('operate'),
        operateTxt;
      operateTxt = '.' + operate + '-btn';
      $operateBtn = $submitBtn.filter(operateTxt);
      $operateType.val(operate);
    });
  
    $dataFrm.submit(function(event) {
      event.preventDefault();
      var $me = $(this),
          packSelected = $packSelectedList.val(),
          packCheck = $AdspaceCheck.filter(':checked').val(),
          targetType = $adspaceBlack.filter(':checked').val();
      // PMP ID Validate

      // console.log(targetType);
      // console.log(packSelected);
      // console.log(packCheck);
      // return;

      if(targetType !== 'no_limit'){
        if (packSelected === '' && packCheck === 'part') {
          event.preventDefault();
          var msg = VAM.j('Please select at least one!');
          if ($rtbTargetPackErr.html() === '')  {
            $rtbTargetPackErr.html('<em class="checky-default-failure">' + msg + '</em>');
            return false;
          }
        };
        if ($rtbTargetPackErr.html() !== '') {
          return false;
        }
      };
      $me.ajaxSubmit({
        beforeSubmit: function() {
          $operateBtn.button('loading');
        },
        success: function (data) {
          var next = $operateBtn.data('operate');
          $operateBtn.button('reset');
          if (data.status === 'success') {
            VamOpMsg.messager(data);
            if (next === 'save-next') {
              window.location.href = VAM.getVar('NEXT_URL') + '?solution_id=' + data.data.id + '&strategy_name=' + strategyName;
            } else {
              window.location.href = 'solution-list';
            };
          } else {
            VamOpMsg.messager(data);
          }
        }
      });
      return false;
    });
  });
});
